package com.juyu.miliao.api.yidun.servcie.impl;

import com.juyu.miliao.api.yidun.constant.AntispamConstant;
import com.juyu.miliao.api.yidun.constant.AntispamReponseContant;
import com.juyu.miliao.api.yidun.servcie.AntispamService;
import com.juyu.miliao.api.yidun.util.HttpClient4Utils;
import com.juyu.miliao.api.yidun.util.YidunUtil;
import com.juyu.miliao.common.constant.ResultConstant;
import com.juyu.miliao.common.domain.Result;
import com.juyu.miliao.common.util.ResultUtil;
import lombok.extern.log4j.Log4j2;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.client.HttpClient;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author jh
 * 14:39
 */
@Service
@Log4j2
public class AntispamServcieImpl implements AntispamService {

	/**
	 * 实例化HttpClient，发送http请求使用，可根据需要自行调参
	 */
	private static HttpClient httpClient = HttpClient4Utils.createHttpClient(100, 20, 10000, 2000, 2000);

	@Override
	public Result onlineCheck(String content) {
		if (StringUtils.isEmpty(content)) {
			return ResultUtil.error(ResultConstant.ERROR_CODE, "文本为空");
		}

		Map<String, String> map = YidunUtil.getCommonParamMap();
		map.put("content", content);
		String signature = YidunUtil.genSignature(AntispamConstant.SECRETKEY, map);
		if (StringUtils.isEmpty(signature)) {
			return ResultUtil.error(ResultConstant.ERROR_CODE, "转换签名错误");
		}
		map.put("signature", signature);

		String response = null;
		try {
            //可以使用restTemplate,有个问题,发过去得是utf-8
			response = HttpClient4Utils.sendPost(httpClient, AntispamConstant.API_URL, map, Consts.UTF_8);
		} catch (Exception e) {
			map.put("content", "内容不打印");
			log.error("msg: {},parms:{}", "调用易盾在线接口失败,网络连接错误", map.toString());
		}

		if (StringUtils.isEmpty(response)) {
			map.put("content", "内容不打印");
			log.error("msg: {},parms:{}", "调用易盾在线接口失败,验证返回空", map.toString());
			return ResultUtil.error(ResultConstant.ERROR_CODE, "验证返回空");
		}

		JSONObject json = JSONObject.fromObject(response);
		if (json == null) {
			return ResultUtil.error(ResultConstant.ERROR_CODE, "验证返回空");
		}
		if (json.get("code") != null && AntispamReponseContant.CODE_SUCCESS == json.getInt("code")) {
			JSONObject resultJson = json.getJSONObject("result");
			//调用成功,分析确定能否处理
			if (AntispamReponseContant.ACTION_SUCCESS == resultJson.getInt("action")) {
				return ResultUtil.success();
			} else {
				return ResultUtil.error(ResultConstant.ERROR_CODE, "含有敏感词汇,请重新输入");
			}

		}
		return ResultUtil.error(ResultConstant.ERROR_CODE, json.getString("msg"));
	}


}
